package com.vic.commons.service;

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import tk.mybatis.mapper.common.Mapper;

import com.vic.commons.dao.BaseDao;
import com.vic.commons.utils.FirstCharacterConvert;
import com.vic.commons.utils.SpringContextUtil;


@Transactional
public class BaseService<T>
{
	@Autowired
	private Mapper<T> mapper;
	
	private Class<T> entityClass;


	@SuppressWarnings({ "unchecked", "rawtypes" })
	public BaseService()
	{
		Type genType = getClass().getGenericSuperclass();
		Type[] params = ((ParameterizedType) genType).getActualTypeArguments();
		entityClass = (Class) params[0];
	}

	@SuppressWarnings("unchecked")
	private BaseDao<T> getDaoApplicationContext()
	{
		String className = entityClass.getSimpleName();
		StringBuilder sb = new StringBuilder(FirstCharacterConvert.firseCharactrtLowerCase(className)).append("Dao");
		return (BaseDao<T>) SpringContextUtil.getBean(sb.toString());
	}
	
	public List<Map<String, Object>> findBySql(String sql){
		return this.getDaoApplicationContext().findBySql(sql);
	}

	public T getById(Object id){
		return mapper.selectByPrimaryKey(id);
	}
	
	public int save(T entity){
        return mapper.insert(entity);
    }

    public int delete(T entity){
        return mapper.deleteByPrimaryKey(entity);
    }
    
    public int list(T entity){
        return mapper.deleteByPrimaryKey(entity);
    }

}
